package com.xingzhe.content.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xingzhe.base.exception.XingZhePlusException;
import com.xingzhe.base.model.PageParams;
import com.xingzhe.base.model.PageResult;
import com.xingzhe.content.mapper.*;
import com.xingzhe.content.model.dto.AddCourseDto;
import com.xingzhe.content.model.dto.CourseBaseInfoDto;
import com.xingzhe.content.model.dto.EditCourseDto;
import com.xingzhe.content.model.dto.QueryCourseParamsDto;
import com.xingzhe.content.model.po.*;
import com.xingzhe.content.service.CourseBaseInfoService;
import com.xingzhe.content.service.CourseTeacherService;
import com.xingzhe.content.service.TeachPlanService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;


@Slf4j
@Service
/**
 * 课程信息管理业务接口实现类
 */
public class CourseBaseInfoServiceImpl implements CourseBaseInfoService {
    @Resource
    private CourseBaseMapper courseBaseMapper;
    @Resource
    private CourseMarketMapper courseMarketMapper;
    @Resource
    private CourseCategoryMapper courseCategoryMapper;
    @Resource
    private CourseTeacherMapper courseTeacherMapper;
    @Resource
    private TeachplanMapper teachplanMapper;
    @Resource
    private TeachplanMediaMapper teachplanMediaMapper;

    /**
     * 分页查询课程
     * @param pageParams  分页参数
     * @param courseParamsDto 查询条件
     * @return
     */
    @Override
    public PageResult<CourseBase> queryCourseBaseList(Long companyId,PageParams pageParams, QueryCourseParamsDto courseParamsDto) {
        //构建查询条件对象
        LambdaQueryWrapper<CourseBase> queryWrapper = new LambdaQueryWrapper<>();
        //构建查询条件，根据课程名称查询
        queryWrapper.like(StringUtils.isNotEmpty(courseParamsDto.getCourseName()),CourseBase::getName,courseParamsDto.getCourseName());
        //构建查询条件，根据课程审核状态查询
        queryWrapper.eq(StringUtils.isNotEmpty(courseParamsDto.getAuditStatus()),CourseBase::getAuditStatus,courseParamsDto.getAuditStatus());
        //根据课程发布状态查询
        queryWrapper.eq(StringUtils.isNotEmpty(courseParamsDto.getPublishStatus()),CourseBase::getStatus,courseParamsDto.getPublishStatus());
//构建查询条件，根据课程发布状态查询
//todo:根据课程发布状态查询 已完成
        //根据培训机构id加条件
        queryWrapper.eq(CourseBase::getCompanyId,companyId);

        //分页对象
        Page<CourseBase> page = new Page<>(pageParams.getPageNo(), pageParams.getPageSize());
        // 查询数据内容获得结果
        Page<CourseBase> pageResult = courseBaseMapper.selectPage(page, queryWrapper);
        // 获取数据列表
        List<CourseBase> list = pageResult.getRecords();
        // 获取数据总数
        long total = pageResult.getTotal();
        // 构建结果集
        PageResult<CourseBase> courseBasePageResult = new PageResult<>(list, total, pageParams.getPageNo(), pageParams.getPageSize());
        return courseBasePageResult;

    }

    /**
     * 新增课程
     * @param companyId 机构id
     * @param dto
     * @return
     */
    @Transactional
    @Override
    public CourseBaseInfoDto createCourseBase(Long companyId, AddCourseDto dto) {
        //参数的合法性校验
       /* if (StringUtils.isBlank(dto.getName())) {
//            throw new RuntimeException("课程名称为空");
            XingZhePlusException.cast("课程名称为空");
        }

        if (StringUtils.isBlank(dto.getMt())) {
            throw new RuntimeException("课程分类为空");
        }

        if (StringUtils.isBlank(dto.getSt())) {
            throw new RuntimeException("课程分类为空");
        }

        if (StringUtils.isBlank(dto.getGrade())) {
            throw new RuntimeException("课程等级为空");
        }

        if (StringUtils.isBlank(dto.getTeachmode())) {
            throw new RuntimeException("教育模式为空");
        }

        if (StringUtils.isBlank(dto.getUsers())) {
            throw new RuntimeException("适应人群为空");
        }

        if (StringUtils.isBlank(dto.getCharge())) {
            throw new RuntimeException("收费规则为空");
        }*/

        //向课程基本信息course_base写入数据
        CourseBase courseBase = new CourseBase();
        BeanUtils.copyProperties(dto,courseBase);//只要属性名称一致就可以拷贝
        courseBase.setCompanyId(companyId);//机构id
        courseBase.setCreateDate(LocalDateTime.now());//新增的时间
        courseBase.setAuditStatus("202002");//审核状态默认为未提交
        courseBase.setStatus("203001");//发布状态为未发布
        int insert = courseBaseMapper.insert(courseBase);

        //向课程营销信息course_market写入
        CourseMarket courseMarket = new CourseMarket();
        BeanUtils.copyProperties(dto,courseMarket);
        courseMarket.setId(courseBase.getId());//与课程基本信息的id关联所以设置一样的
        int i = saveCourseMarket(courseMarket);
        if (i<1||insert<1){
            log.error("创建课程时出错：{}",dto);
            throw new XingZhePlusException("创建课程时出错");
        }
        //还要将保存完的课程信息返回前端
        return getCourseBaseInfo(courseBase.getId());
    }

    /**
     * 单独定义一个保存营销信息的方法,逻辑：存在则更新,不存在则添加
     * @param courseMarket
     * @return
     */
    private int saveCourseMarket(CourseMarket courseMarket){
        //参数校验合法性
        //如果收费规则不填则抛异常
        String charge = courseMarket.getCharge();
        if (StringUtils.isEmpty(charge)){
            throw new XingZhePlusException("收费规则为空");
        }
        //如果课程收费，但是价格填写不正确或者没填要抛异常
        if (charge.equals("201001")){
            if (courseMarket.getPrice()==null||courseMarket.getPrice().floatValue()<=0){
//                throw new RuntimeException("课程的价格不能为空并且必须大于0");
                throw new XingZhePlusException("课程的价格不能为空并且必须大于0");
            }
        }
        //从数据库查询这个营销信息，如果有则更新，没有则新增
        Long id = courseMarket.getId();
        CourseMarket market = courseMarketMapper.selectById(id);
        if (market ==null){
            //没有则直接插入
           return courseMarketMapper.insert(courseMarket);
        }
        BeanUtils.copyProperties(courseMarket,market);//将传进来的新数据拷贝覆盖到旧数据
        market.setId(courseMarket.getId());
        //更新
        return courseMarketMapper.updateById(market);
    }

    /**
     * 查询课程信息
     * @param courseId
     * @return
     */
    @Override
    public CourseBaseInfoDto getCourseBaseInfo(Long courseId){
        //从课程基本信息表查询
        CourseBase courseBase = courseBaseMapper.selectById(courseId);
        if (courseBase==null){
            return null;
        }
        //从课程营销信息表查询
        CourseMarket courseMarket = courseMarketMapper.selectById(courseId);

        //组装要返回的数据
        CourseBaseInfoDto courseBaseInfoDto = new CourseBaseInfoDto();
        BeanUtils.copyProperties(courseBase,courseBaseInfoDto);
        if (courseMarket!=null) {
            BeanUtils.copyProperties(courseMarket, courseBaseInfoDto);
        }
        //还有一个课程分类的名称要去课程分类表查询
        CourseCategory courseCategoryMt = courseCategoryMapper.selectById(courseBase.getMt());//一级分类
        courseBaseInfoDto.setMtName(courseCategoryMt.getName());

        CourseCategory courseCategorySt = courseCategoryMapper.selectById(courseBase.getSt());//二级分类
        courseBaseInfoDto.setStName(courseCategorySt.getName());
        return courseBaseInfoDto;
    }

    /**
     * 修改课程信息
     * @param companyId 机构id
     * @param editCourseDto 课程信息
     * @return
     */
    @Override
    public CourseBaseInfoDto updateCourseBase(Long companyId, EditCourseDto editCourseDto) {
        //拿到课程id
        Long id = editCourseDto.getId();
        CourseBase courseBase = courseBaseMapper.selectById(id);
        if (courseBase==null){
            XingZhePlusException.cast("课程不存在");
        }
        CourseMarket courseMarket = courseMarketMapper.selectById(id);

        //数据合法性校验
        //根据具体的业务逻辑去校验
        //本机构只能修改本机构的课程
        if (!companyId.equals(courseBase.getCompanyId())){
            XingZhePlusException.cast("只能修改自己机构的课程!");
        }

        //将新的数据拷贝到旧数据
        BeanUtils.copyProperties(editCourseDto,courseBase);
        BeanUtils.copyProperties(editCourseDto,courseMarket);

        //更新时间
        courseBase.setChangeDate(LocalDateTime.now());

        //更新数据库的课程基本信息
        int i = courseBaseMapper.updateById(courseBase);
        if (i<=0){
            XingZhePlusException.cast("课程基本信息修改失败");
        }
        courseMarketMapper.updateById(courseMarket);

        //查询最新的课程信息,并返回前端
        return  getCourseBaseInfo(id);

    }

    @Transactional
    @Override
    public CourseBase deleteCourse(Long courseId) {
        if (!courseBaseMapper.selectById(courseId).getAuditStatus().equals("202002")){
            XingZhePlusException.cast("课程的审核状态为未提交才能删除哦");
            return null;
        }
        //1.先删除课程教师信息
        LambdaQueryWrapper<CourseTeacher> queryWrapperCourseTeacher = new LambdaQueryWrapper<>();
        queryWrapperCourseTeacher.eq(CourseTeacher::getCourseId,courseId);
        courseTeacherMapper.delete(queryWrapperCourseTeacher);

        //2.删除课程计划信息及附带对应的媒资
        LambdaQueryWrapper<Teachplan> queryWrapperTeachPlan = new LambdaQueryWrapper<>();
        queryWrapperTeachPlan.eq(Teachplan::getCourseId,courseId);
        teachplanMapper.delete(queryWrapperTeachPlan);
        LambdaQueryWrapper<TeachplanMedia> queryWrapperMedia = new LambdaQueryWrapper<>();
        queryWrapperMedia.eq(TeachplanMedia::getCourseId,courseId);
        teachplanMediaMapper.delete(queryWrapperMedia);


        //3.删除课程营销信息
        courseMarketMapper.deleteById(courseId);

        //4.最后删除课程基本信息
        courseBaseMapper.deleteById(courseId);
        return null;
    }

}
